package com.yangmin.springcloud.service.impl;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.yangmin.springcloud.service.PaymentHystrixService;
import org.springframework.stereotype.Service;

@Service
public class PaymentHystrixServiceImpl implements PaymentHystrixService {
    @Override
    public String paymentHystrixService_Ok(Integer id) {
        return "线程池：" + Thread.currentThread().getName() + " 方法：paymentHystrixService_Ok"
                + "id:" + id + "哈哈哈~";
    }

    @Override
    @HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
    })
    public String paymentHystrixService_Outtime(Integer id) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池：" + Thread.currentThread().getName() + " 方法：paymentHystrixService_timeout "
                + "id: " + id + "哭哭哭~";
    }

    /**
     * 注意降级服务方法的参数要与对应的方法保持一致，不然会爆错，爆找不到fallback的方法
     * @param id
     * @return
     */
    public String paymentInfo_TimeOutHandler(Integer id) {
        return "我是服务提供者8001,对方支付系统繁忙请10秒钟后再试或者自己运行出错请检查自己,o(╥﹏╥)o";
    }

    // 熔断
    @Override
//    @HystrixCommand(fallbackMethod = "paymentHystrixCircuitBreakerMethod", commandProperties = {
//            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),
//            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
//            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),
//            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60")})
    public String paymentCircuitBreaker(Integer id) {
//        if (id < 0) {
//            throw new RuntimeException("id 不能为负数");
//        }
        return "线程池：" + Thread.currentThread().getName() + " 方法：paymentCircuitBreaker "
                + "id " + id + " 流水号：" + IdUtil.randomUUID();
    }

    public String paymentHystrixCircuitBreakerMethod(Integer id) {
        return "抱歉！！ id 不能为负数，请稍后再试";
    }
}
